package com.omkarpatil.learningjpa2.mapping.onetomany.jointable;

import javax.persistence.EntityManager;

import com.omkarpatil.learningjpa2.util.EntityManagerFactoryFactory;

public class TestDriver {

	public static void main(String[] args) {
		EntityManager em1 = EntityManagerFactoryFactory.getEntityManagerFactory().createEntityManager();
		em1.getTransaction().begin();
		
		System.out.println("##### Adding two employees ...");
		Employee emp1 = new Employee("Mr. X");
		em1.persist(emp1);
		
		Employee emp2 = new Employee("Mr. Y");
		em1.persist(emp2);
				
		System.out.println("Adding a separtment and two enployees to it ...");
		Department dept1 = new Department("Development");
		
		dept1.addEmployee(emp1);
		dept1.addEmployee(emp2);
		
		em1.persist(dept1);
		
		em1.getTransaction().commit();
		em1.close();
		
		EntityManager em2 = EntityManagerFactoryFactory.getEntityManagerFactory().createEntityManager();
		em2.getTransaction().begin();
		
		em2.merge(dept1);
		System.out.println("##### Let's see how many employees the department has ...");
		
		Employee mrY = null;
		for(Employee e : dept1.getEmployees()) {
			System.out.printf("##### Employee name : %s\n", e.getName());
			if (e.getName().equals("Mr. Y")) {
				mrY = e;
			}
		}
		System.out.println("##### Moving away Mr. Y from the department ...");
		dept1.removeEmployee(mrY);
		
		em2.getTransaction().commit();
		em2.close();
		
		EntityManager em3 = EntityManagerFactoryFactory.getEntityManagerFactory().createEntityManager();
		em3.getTransaction().begin();
		
		em3.merge(dept1);
		System.out.printf("##### How many employees still left in department? %s\n", dept1.getEmployees().size());
		
		em3.getTransaction().commit();
		em3.close();
	}

}
